package com.miyake.client.datamanage;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Panel;
import com.miyake.client.DataService;
import com.miyake.client.DataServiceAsync;
import com.miyake.client.tools.ClickableImage;

abstract public class ShowFixedPlot {
	private DataServiceAsync service = DataService.Util.getInstance();
	private NodeUpdateHandler udpateHandler;
	abstract protected void onTextUpdate(String nodeKey);
	
	public ShowFixedPlot(String key, Panel panel, int width, int height, NodeUpdateHandler handler) {
		this.udpateHandler = handler;
		showPlot(key, panel, width, height);
	}
	public ShowFixedPlot(NodeProperty node, Panel panel, int width, int height, NodeUpdateHandler handler) {
		this.udpateHandler = handler;
		showPlot(node.getKey(), panel, width, height);
	}
	public ShowFixedPlot(String key, Panel panel, int width, int height) {
		showPlot(key, panel, width, height);
	}
	public ShowFixedPlot(NodeProperty node, Panel panel, int width, int height) {
		showPlot(node.getKey(), panel, width, height);
	}
	protected void showPlot(final String key, Panel panel, int width, int height) {
		//final HTML image = new HTML();

		final Image image;
		if (udpateHandler != null) {
			image = new ClickableImage();
		}
		else {
			image = new Image();
		}
		image.setAltText("Loading...");
		panel.add(image);
		image.setPixelSize(width, height);
		image.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				if (udpateHandler != null) {
					udpateHandler.onNodeChange(key);
				}
			}
		});
		//final HTML label = new HTML();
		//panel.add(label);
		service.getPlotURL(key, width, height, new AsyncCallback<String>() {
			@Override
			public void onFailure(Throwable caught) {
				//Window.alert(caught.getMessage());
				image.setAltText(caught.getMessage());
			}

			@Override
			public void onSuccess(String result) {
				image.setAltText(result);
				image.setUrl(result);
				//label.setText(result);
				//label.setHTML("<div align=\"center\"><img src=\"" + result + "\"></div>");
			}
		});
		
	}
}
